package cn.amossun.starter.mybatis.data.security.loader;

import com.google.common.cache.CacheLoader;
import com.google.common.util.concurrent.JdkFutureAdapters;
import com.google.common.util.concurrent.ListenableFuture;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020/03/01 15:27
 **/
@Slf4j
@AllArgsConstructor
public class OrmConfigCacheLoader extends CacheLoader<String, Object> {

    private final RedisTemplate amosRedisTemplate;

    private final ThreadPoolTaskExecutor amosThreadPoolTaskExecutor;

    @Override
    public Optional<Object> load(String key) {
        log.info("Guava OrmConfigCacheLoader load更新key: {} ", key);
        return generateCacheValue(key);
    }

    @Override
    public ListenableFuture<Object> reload(String key, Object oldValue) throws Exception {
        Future<Object> future = amosThreadPoolTaskExecutor.submit(new Callable<Object>() {
            @Override
            public Optional<Object> call() throws Exception {
                log.info("Guava OrmConfigCacheLoader reload定时异步更新key: {}", key);
                return generateCacheValue(key);
            }
        });
        return JdkFutureAdapters.listenInPoolThread(future);
    }

    Optional<Object> generateCacheValue(String key) {
        return Optional.ofNullable(amosRedisTemplate.opsForValue().get(key));
    }

}
